package cn.brilliantfuture.commentry.warn;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import cn.brilliantfuture.commentry.util.DateTimeHelper;
import cn.brilliantfuture.commentry.util.HttpUtil;
import cn.brilliantfuture.commentry.util.JDBCDataSource;

/**
 * 
 * Title: Cabinet Platform
 * 
 * Author: GuoQingBiao
 * 
 * Date: 2012-3-14
 * 
 * Description:
 * 
 */

public class TakeoutWarnTask extends TimerTask {
	private static final long serialVersionUID = 1L;

	private static Logger logger = Logger.getLogger(TakeoutWarnTask.class);
	
	/**
	 * 彩信猫信息通道
	 */
	public static final int MMS_CAT_CHANNEL = 1;
	
	/**
	 * 企信通DIY09信息通道
	 */
	public static final int QXT_DIY09_CHANNEL = 2;

	// 发送次数
	private static Map<Integer, Date> warnRecordMap = new HashMap<Integer, Date>();

	@SuppressWarnings("static-access")
	@Override
	public void run() {

		logger.info("Send warn message ...");

		// 当前时间字符串
		Date nowDate = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(nowDate);

		// 时间晚于早上8点 早于晚上22点发送短信提醒
		if (calendar.get(calendar.HOUR_OF_DAY) >= 8 && calendar.get(Calendar.HOUR_OF_DAY) <= 22) {
			Connection conn = null;
			PreparedStatement pstm = null;
			ResultSet rs = null;

			try {
				// 查询配送记录表
				String sql = "select sgpn.storage_grid_purchaser_news_id, p.phone, p.language, sgpn.arrival_time, lo.description, l.lockers_name, ug.name as group_name, ug.sms_channel, ug.hotline from storage_grid_purchaser_news sgpn inner join purchaser p on p.purchaser_id = sgpn.purchaser_id inner join lockers l on l.lockers_id = sgpn.lockers_id inner join location lo on l.location_id = lo.location_id inner join user_group ug on ug.group_id = sgpn.group_id where sgpn.closing = 0 and delivery = 1 and pick = 0 and sgpn.takeaway_time is null";
				List<Object[]> sgpnList = new ArrayList<Object[]>();

				conn = JDBCDataSource.getConnection();
				pstm = conn.prepareStatement(sql);
				rs = pstm.executeQuery();
				while (rs.next()) {
					Object[] objs = new Object[9];
					objs[0] = rs.getObject("storage_grid_purchaser_news_id");
					objs[1] = rs.getObject("phone");
					objs[2] = rs.getObject("arrival_time");
					objs[3] = rs.getObject("description");
					objs[4] = rs.getObject("lockers_name");
					objs[5] = rs.getObject("group_name");
					objs[6] = rs.getObject("sms_channel");
					objs[7] = rs.getObject("language");
					objs[8] = rs.getObject("hotline");
					sgpnList.add(objs);
				}

				// 遍历所有未取货仓格
				if (sgpnList != null && sgpnList.size() > 0) {

					Map<Integer, Date> tempRecordMap = new HashMap<Integer, Date>();
					tempRecordMap.putAll(warnRecordMap);
					warnRecordMap.clear();

					for (int i = 0; i < sgpnList.size(); i++) {
						Object[] obj = sgpnList.get(i);
						Date sendTime = null;
						// 获取是否之前发送过信息及信息发送时间
						if (tempRecordMap.containsKey(Integer.parseInt(obj[0]
								.toString()))) {
							sendTime = tempRecordMap.get(Integer
									.parseInt(obj[0].toString()));
						}

						boolean flag = false;
						if (null == sendTime) {
							Date deliveryTime = DateTimeHelper.strToDateTime(
									obj[2].toString(),
									DateTimeHelper.DEFAULT_DATE_TIME_FORMAT);

							if ((nowDate.getTime() - deliveryTime.getTime()) >= (4 * 60 * 60 * 1000L)) {
								flag = true;
							} else {
								flag = false;
							}

						} else {
							if ((nowDate.getTime() - sendTime.getTime()) >= (4 * 60 * 60 * 1000L)) {
								flag = true;
							} else {
								flag = false;
							}
						}

						if (flag) {
							rs = null;
							pstm = null;
							
							String message = null;
							String smsSql = "select sms_info.sms_content from sms_info where sms_info.deleted = 0 and sms_info.sms_use = 6 and sms_info.apply_orient = 4 and sms_info.language_info_id = " + Integer.parseInt(obj[7].toString());
							
							pstm = conn.prepareStatement(smsSql);
							rs = pstm.executeQuery();

							if (rs.next())
								message = rs.getString("sms_content");

							if (null != message) {
								Object[] objs = {obj[3].toString() + obj[4].toString(), obj[8] };
								message = MessageFormat.format(message, objs);
								
								StringBuffer sb = new StringBuffer();

								if (MMS_CAT_CHANNEL == Integer.parseInt(obj[6].toString())){
									message += "【" + obj[5].toString() + "】";
								}

								try {
									message = URLEncoder.encode(message, "utf8");
								} catch (UnsupportedEncodingException e) {
									logger.error(e.getMessage());
								}

								sb.append("http://sms.acsm.cn/smsservice-web");
								if (MMS_CAT_CHANNEL == Integer.parseInt(obj[6].toString())){
									sb.append("/SMSMessageServiceChannel");
								} else if (QXT_DIY09_CHANNEL == Integer.parseInt(obj[6].toString())){
									sb.append("/CMPPMessageServiceChannel");
								}

								sb.append("?username=acsm&passwd=acsm@197&phones=");
								sb.append(obj[1].toString());
								sb.append("&content=");
								sb.append(message);

								String returnValue = HttpUtil.getInvoke(sb.toString());
								
								logger.info("Return value : " + returnValue);
							}

							warnRecordMap.put(Integer.parseInt(obj[0]
									.toString()), nowDate);
						} else {
							warnRecordMap.put(Integer.parseInt(obj[0]
									.toString()), sendTime);
						}
					}
				}

			} catch (SQLException e1) {
				logger.error(e1.toString());
			} finally {
				JDBCDataSource.closeResource(conn, pstm, rs);
			}
		}
	}

}